package com.ck.core.interceptor;

import com.ck.annotation.PermissionRequired;
import com.ck.constant.CacheConstant;
import com.ck.util.AjaxUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 节目编辑客户端权限验证
 *
 * @author linqiang
 * @date 2018-09-19 16:02
 */
@Component
public class PermissionInterceptor implements HandlerInterceptor {
    private static Logger logger = LoggerFactory.getLogger(PermissionInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (hasPermission(handler, request)) {
            return true;
        }
        try {
            AjaxUtils.writeNeedLoginResultForAjax(response);
        } catch (IOException e1) {
            logger.error(e1.getMessage(), e1);
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

    /**
     * 客户端是否有访问权限
     *
     * @param handler
     * @return
     */
    private boolean hasPermission(Object handler, HttpServletRequest request) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            PermissionRequired clientPermissionRequired = handlerMethod.getMethod().getAnnotation(PermissionRequired.class);
            // 如果方法上的注解为空 则获取类的注解
            if (clientPermissionRequired == null) {
                clientPermissionRequired = handlerMethod.getMethod().getDeclaringClass().getAnnotation(PermissionRequired.class);
            }
            // 如果标记了注解，则判断是否包含token
            if (clientPermissionRequired != null) {
                String token = request.getHeader(CacheConstant.CK_TOKEN_CACHE_NAME);
                return !StringUtils.isBlank(token);
            }
        }
        return true;
    }
}
